

<template>
  <div>

    <!-- table 组件-->
    <dyn-table
            :queryParams="query"
            :listBtnObj="dynTableData.listBtnObj"
            :listTable="dynTableData.listTable"
            :eventName="eventName"
            ref="dynTableBox"
    />
    <!-- 查看表单 -->
    <!-- 新建表单 -->
    <principalPart-add ref="principalPartAdd"  @created="doQueryList({ page: 1 })"/>
    <!-- 编辑表单 -->
    <principalPart-edit ref="principalPartEdit"  @updated="doQueryList({})"/>

  </div>
</template>

<script>
import principalPartAdd from './add'
import principalPartEdit from './edit'

import { getOffsetTop, queryToString } from '@/utils/public'
import principalPartApi from '@/api/platformLiyonghui/principalPart'

import elDragDialog from '@/directive/el-drag-dialog'
import Pagination from '@/components/Pagination'
import DynTable from '@/components/DynTable'
import specialAttr from '@/utils/special-attr'
import tableConfigApi from '@/api/platformLiyonghui/tableConfig'
import dynTableApi from '@/api/platformLiyonghui/dynTable'



export default {
  name: 'PrincipalPartTable',
  directives: { elDragDialog },
  components: {
    DynTable,
    Pagination,
    principalPartAdd,
    principalPartEdit
  },
  data() {
    return {
        // 组件内部调用的查询和重置方法
      eventName: {
        search: 'handleQuery',
        reset: 'handleReset',
        drags: 'handleDrags',//拖拽区确定按钮
        order: 'sortChange',
        page: 'handlePage'
      },
      // 动态表格属性
      dynTableData: {
        listBtnObj: [],
        listTable: {},
        inLineBtnList: []
      },
      listQuery: {},
      tableHeight: -1,
      options: {
      },
      query: {
        pageNum: 1,
        pageSize: 20,
        sortBy: 'id',
        sortOrder: 'desc',
        q: ''
      },
    }
  },
  created() {
    Promise.all([
    ]).then(() =>{
    
      const objDatas = [];
      const code = sessionStorage.getItem('routerCode');
      const menus = JSON.parse(sessionStorage.getItem('routerMenus'));
      console.log(code)
      console.log(menus)
      if(menus!=null){
        menus.forEach((item) => {
          if(item.menuCode==code){
            objDatas.push(item)
          }
        })
      }
      const objData = objDatas[0]
      this.genDynTable(objData);
    })
  },
  methods: {



    // 组装数据
    genDynTable(objData){
      this.dynTableData.listBtnObj = objData.listBtnObj
      this.dynTableData.listTable = objData.listTable
      //获取字典项
      const dictionaryEntry = JSON.parse(sessionStorage.getItem('constCode'))
      objData.listTable.tableHeader.forEach(headerField => {
        // 组装枚举数据
        if(headerField.fieldSpecialType === specialAttr.fieldSpecialType.ENUM_TYPE.code){
          console.log('ENUM_TYPE',headerField.dicTypeData)
          if(headerField.filtered){
            // headerField.filterQuery.options = this.$store.getters.dictList[headerField.dicTypeData].map(item => ({ label: item.name, value: item.value}))
            headerField.filterQuery.options = []
            dictionaryEntry.forEach((item) => {
              if(item.constCode == headerField.dicTypeData){
                headerField.filterQuery.options.push({ label: item.name, value: item.value })
              }
            })
            console.log('headerField.filterQuery.options',headerField.filterQuery.options)
          }
          // 方法名称
          headerField.webFilter = 'findEnumLabel'
          // 数组名称
          // headerField.webFilterArr = this.$store.getters.dictList[headerField.dicTypeData].map(item => ({ label: item.name, value: item.value}))
          headerField.webFilterArr = []
          dictionaryEntry.forEach((item) => {
            if(item.constCode == headerField.dicTypeData){
              headerField.webFilterArr.push({ label: item.name, value: item.value })
            }
          })
          // 属性名称(枚举不需要属性名称)
          headerField.webFilterProp = 'label'
          headerField.webFilterValue = 'value'
        // 组装外键数据
        }else if(headerField.fieldSpecialType === specialAttr.fieldSpecialType.FK_TYPE.code){
          console.log('FK_TYPE')
          if(headerField.filtered){
            headerField.filterQuery.options = this.options[headerField.foreignData]
          }
          // 方法名称
          headerField.webFilter = 'findForeignKey'
          // 数组名称
          headerField.webFilterArr = this.options[headerField.foreignData]
          // 属性名称
          headerField.webFilterProp = 'label'
          //对比值
          headerField.webFilterValue = 'value'
          if (headerField.editType === 'tree_select') {
          headerField.webFilterValue = 'id'
          }
        // 组装多对多实体数据
        }else if(headerField.fieldSpecialType === specialAttr.fieldSpecialType.MTM_TYPE.code){
          if(headerField.filtered){
              headerField.filterQuery.options = this[headerField.webEntityData]
          }
        // 组装其他数据
        }else if(headerField.fieldSpecialType === specialAttr.fieldSpecialType.OTHER_WEB.code){
          console.log('OTHER_WEB')
          if(headerField.filtered){
            headerField.filterQuery.options = this[headerField.webEntityData]
          }
        }
        if(headerField.column == "workflowState"){
          // 方法名称
          headerField.webFilter = 'findEnumLabel'
          // 数组名称
          // headerField.webFilterArr = this.$store.getters.dictList[headerField.dicTypeData].map(item => ({ label: item.name, value: item.value}))
          headerField.webFilterArr = [
            { label: '执行中', value: 0 },
            { label: '草稿', value: 1 },
            { label: '驳回', value: 2 },
            { label: '提交', value: 3 },
            { label: '通过', value: 4 },
            { label: '不通过', value: 5 },
            { label: '完成', value: 6 },
          ]
          // 属性名称(枚举不需要属性名称)
          headerField.webFilterProp = 'label'
          headerField.webFilterValue = 'value'
        }
      })
      // 获取行内按钮集合
      objData.listBtnObj.forEach(item=> {
          if(item.isLine === true){
              item.isShow = true
              this.dynTableData.inLineBtnList.push(item)
          }
      })

      this.doQueryList({ page: 1 })
    },
    /**
     * 触发后端排序
     */
    sortChange({ name, order }) {
      this.$set(this.query,'sortBy',name)
      if (order === 'ascending') {
        this.$set(this.query,'sortOrder','asc')
      } else {
        this.$set(this.query,'sortOrder','desc')
      }
      this.doQueryList({ page: 1 })
    },
    /**
     * 触发搜索操作
     */
    handleQuery(queryVariable) {
      this.$set(this.query,'q',queryToString(queryVariable))
      this.doQueryList({ page: 1 })
    },
    //拖拽区确定按钮
    handleDrags(tableHeaders){
      const dynTableHeader = []
      tableHeaders.forEach(item => {
        const header = {
          column: item.column,
          showed: item.showed,
          fixed: item.fixed,
          filtered: item.filtered
        }
        dynTableHeader.push(header)
      })
      const {tenantId, groupId, orgId, userId, account} = JSON.parse(sessionStorage.getItem('userinfos')) || {};
      const customTableColumn = {
        id: null,
        menuCode: sessionStorage.getItem('routerCode'),
        tenantId: tenantId,
        groupId: groupId,
        orgId: orgId,
        userId: userId,
        account: account,
        dynTableHeader: dynTableHeader
      }
      tableConfigApi.saveCustomTableColumn(customTableColumn).then(res => {
        if (res.code === '000000') {
          this.$message({
            type: 'success',
            message: '保存成功!'
          })
          this.dynTableData.listTable.tableHeader = JSON.parse(JSON.stringify(tableHeaders))
          this.$nextTick(()=>{
            this.$refs.dynTableBox.doLayoutTable()
          })
          // 刷新动态表单表格
          dynTableApi.getDynTable(tenantId).then(res => {
            sessionStorage.setItem("routerMenus", JSON.stringify(res.data));
          }).catch(err => {
            console.log(err)
          })
          this.doQueryList({ page: 1 })
        } else {
          this.$message({
            type: 'error',
            message: res.message
          })
        }
      })
    },
    // 重置按钮方法
    handleReset() {
      this.query = {
        pageNum: 1,
        pageSize: 20,
        sortBy: 'id',
        sortOrder: 'desc',
        q: ''
      }
      this.doQueryList({ page: 1 })
    },
    //分页
    handlePage(param){
      this.doQueryList({ page: param.pageNum, limit: param.pageSize })
    },
    /**
     * 执行列表查询
     */
    doQueryList({ page, limit }) {
      if (page) {
        this.query.pageNum = page
      }
      if (limit) {
        this.query.pageSize = limit
      }
      this.listLoading = true

      const args = Object.assign({}, this.query)
      this.listLoading = true
      return principalPartApi.finds(args)
        .then(res => {
          res.data.list.forEach(item=>{
            item.operation = JSON.parse(JSON.stringify(this.dynTableData.inLineBtnList))
            item.operation.forEach(op =>{
              if (op.isStarted) {
                let {label, labelFalse} = op;
                if (!item[op.code]) {
                  op.label = labelFalse;
                }
                item[op.code] = item[op.code] ? labelFalse : label
              }
            })
          })
          this.$set(this.dynTableData.listTable,'total',res.data.total)
          this.$set(this.dynTableData.listTable,'tableData',res.data.list)
        })
    },

    /**
     * 删除单条记录
     */
    handleDeleteSingle(row) {
      return this.$common.confirm('是否确认删除')
        .then(() => {
          this.listLoading = true
          principalPartApi.del(row.id)
          .then(() => {
                this.$common.showMsg('success', '删除成功')
                return this.doQueryList({ page: 1 })
          })
        })
        .catch(() => {
          this.$message({type: 'info',message: '已取消删除'})
        })
    },
    /**
     * 批量删除记录
     */
    handleDeleteBatch(listRow) {
      if (listRow.length <= 0) {
        this.$common.showMsg('warning', '请选择主体单位')
        return
      }
      return this.$common.confirm('是否确认删除')
        .then(() =>{
            this.listLoading = true
            principalPartApi.deleteBatch(listRow.map(row => row.id))
            .then(() => {
                this.$common.showMsg('success', '删除成功')
                return this.doQueryList({ page: 1 })
            }).catch(()=>{
                this.listLoading = false
            })
        }).catch(() => {
              this.$message({
              type: 'info',
              message: '已取消删除'
          })
        })
    },


    /**
     * 打开新建表单
     */
    handleCreate() {
      this.$refs.principalPartAdd.handleCreate()
    },
    /**
     * 打开编辑表单
     */
    handleUpdate(row) {
      this.$refs.principalPartEdit.handleUpdate(row)
    },
    exportExcel() {
      this.export()
    },
    exportAllExcel() {
      this.listLoading = true
      const args = Object.assign({}, this.query)
      args.total = this.dynTableData.listTable.total
      principalPartApi.exportExcelAll(args).then(res=>{
        this.listLoading = false
        let link = document.createElement('a');
        let body = document.querySelector('body');
        link.href = window.URL.createObjectURL(res);
        link.download = "记录.xlsx";
        // fix Firefox
        link.style.display = 'none';
        body.appendChild(link);
        link.click();
        body.removeChild(link);
        window.URL.revokeObjectURL(link.href);
      })
    },
    export(pageNum) {
      this.listLoading = true
      const args = Object.assign({}, this.query)
      if (pageNum) {
        args.pageNum = pageNum
      }
      principalPartApi.exportExcel(args).then(res=>{
        this.listLoading = false
        let link = document.createElement('a');
        let body = document.querySelector('body');
        link.href = window.URL.createObjectURL(res);
        link.download = "记录（第" + args.pageNum + "页）.xlsx";
        // fix Firefox
        link.style.display = 'none';
        body.appendChild(link);
        link.click();
        body.removeChild(link);
        window.URL.revokeObjectURL(link.href);
      })
    },
    importExcel(excelFile){
      this.listLoading = true
        principalPartApi.importExcel(excelFile).then(res=>{
          if (res.code === '000000') {
            this.$message({
              type: 'success',
              message: '导入成功!'
            })
            this.doQueryList({ page: 1 })
          }else{
            this.$message({
              type: 'error',
              message: res.message
            })
            this.listLoading = false
          }
        }).catch(()=>{
          this.listLoading = false
        })
      }
  }
}
</script>
